package com.huak.zookeeper.spel;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author liuhuan
 * @date 2018/9/15 15:44
 * @description
 */
@Component
@Aspect
@Slf4j
public class HelloAspect {

    @Pointcut("@annotation(com.huak.zookeeper.spel.Hello)")
    public void hello(){

    }

    @Before("hello()")
    public void doHello(JoinPoint joinPoint)throws Exception{
        //获取代理方法的签名
        Signature signature =joinPoint.getSignature();
        Object args[]= joinPoint.getArgs();
        log.info("方法上的参数:{}", Arrays.toString(args));

        //获取方法全限定名
        String methodFullName=signature.toString();

        //获取方法名
        String methodName = methodFullName.substring(methodFullName.lastIndexOf(".")+1, methodFullName.indexOf("("));

        //获取代理对象的类对象
        Class clazz=joinPoint.getTarget().getClass();

        Method method=null;
        //获取所有的方法
        Method methods[]=clazz.getMethods();
        //获取切面的方法
        for (Method method1:methods) {
            if(method1.getName().equals(methodName)){
                method=method1;
                break;
            }
        }
        //获取方法上的注解
        Annotation annotation= method.getAnnotation(Hello.class);

        Hello hello=(Hello)annotation;
        ExpressionParser parser =new SpelExpressionParser();
        Expression exp=parser.parseExpression(hello.value());
        String value =exp.getValue(String.class);


        log.info("方法上的注解:{}", value);
    }
}
